package com.ray.generator.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ray.generator.entity.TableEntity;
import com.ray.generator.mapper.GeneratorMapper;
import com.ray.generator.service.GeneratorService;
import com.ray.generator.utils.GenUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.ByteArrayOutputStream;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipOutputStream;

/**
 * @author Ray
 * @date 2018/12/19
 * 代码生成器 服务层处理
 */
@Service
public class GeneratorServiceImpl implements GeneratorService {

    @Autowired
    private GeneratorMapper mySQLGeneratorMapper;

    /**
     * 查询表信息
     * @param tableName 表名
     */
    @Override
    public Map<String, String> queryTable(String tableName) {
        return mySQLGeneratorMapper.queryTable(tableName);
    }

    /**
     * 查询列信息
     * @param tableName 表名
     */
    @Override
    public List<Map<String, String>> queryColumns(String tableName) {
        return mySQLGeneratorMapper.queryColumns(tableName);
    }

    /**
     * 查询表列表(模糊)
     * @param page 分页
     * @param tableName 表名
     */
    @Override
    public IPage<TableEntity> myQueryList(Page page, String tableName) {

        return mySQLGeneratorMapper.myQueryList(page, tableName);
    }

    /**
     * 生成代码
     * @param tableNames 表名s
     */
    @Override
    public byte[] generatorCode(String[] tableNames) {
        // 字节数组输出流
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        // zip输出流
        ZipOutputStream zip = new ZipOutputStream(outputStream);

        for(String tableName : tableNames){
            //查询表信息
            Map<String, String> table = queryTable(tableName);
            //查询列信息
            List<Map<String, String>> columns = queryColumns(tableName);
            //生成代码
            GenUtils.generatorCode(table, columns, zip);
        }
        IOUtils.closeQuietly(zip);
        return outputStream.toByteArray();
    }

}
